package com.qs.javame.thread1028.future;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 使用Future实现异步返回结果，处理业务（实测：多线程异步回调确实小了高，基本上以并发任务中执行耗时最长的任务为最终执行时间）
 *
 * 需求：分别从oracle、mysql数据库中导出数据，存储在同一个目录下，并打成压缩包，发送出去。
 */
public class TestFuture3 {

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + "-开始执行。。");
        long startTime = System.currentTimeMillis();
        //使用线程池创建两个线程
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        //从oracle库中查询、导出数据，返回文件路径
        Future<String> oracleResultFuture = executorService.submit(new DownloadOracleTask("t_order"));

        //从mysql数据库中查询、导出数据，返回文件路径
        Future<String> mysqlResultFuture = executorService.submit(new DownloadMysqlTask("t_customer"));

        //上述两步操作都完成了，开始文件打包
        try {
            //主线程完成打包业务等耗时操作
            System.out.println(Thread.currentThread().getName() + "-处理打包之前的耗时业务。。。");
            Thread.sleep(3000);

            //获取异步调用返回路径结果
            List<String> documentPaths = new ArrayList<>();
            documentPaths.add(oracleResultFuture.get());
            documentPaths.add(mysqlResultFuture.get());
            System.out.println(Thread.currentThread().getName() + "-文件已经打包成功，文件包含：" + documentPaths);

            executorService.shutdown();
            System.out.println(Thread.currentThread().getName() + "-共耗时：" + (System.currentTimeMillis() - startTime)/1000 + "s");
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

}

class DownloadOracleTask implements Callable<String> {

    private String tableName;

    public DownloadOracleTask(String tableName) {
        this.tableName = tableName;
    }

    @Override
    public String call() throws Exception {
        System.out.println(Thread.currentThread().getName() + "-开始查询并导出oracle数据，导出表为：" + tableName);
        //模拟导出表操作，耗时4s
        Thread.sleep(4000);
        return "/user/oracleData.txt";
    }
}

class DownloadMysqlTask implements Callable<String> {

    private String tableName;

    public DownloadMysqlTask(String tableName) {
        this.tableName = tableName;
    }

    @Override
    public String call() throws Exception {
        System.out.println(Thread.currentThread().getName() + "-开始查询并导出mysql数据，导出表为：" + tableName);
        //模拟导出表操作，耗时2s
        Thread.sleep(2000);
        return "/user/mysqlData.txt";
    }
}


